package com.ly.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j
@ServerEndpoint("/websocket/{sid}")  // 接口路径 ws://localhost:8081/webSocket
public class WebSocket {

    private static final AtomicInteger onlineSessionClientCount = new AtomicInteger(0);
    private static final Map<String, Session> onlineSessionClientMap = new ConcurrentHashMap<>();

    private String sid;
    private Session session;

    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value="sid")String sid) {
        onlineSessionClientMap.put(sid, session);
        onlineSessionClientCount.incrementAndGet();
        this.sid = sid;
        this.session = session;
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        onlineSessionClientMap.remove(sid);
        onlineSessionClientCount.decrementAndGet();
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message
     */
    @OnMessage
    public String onMessage(String message) {
        System.out.println(message);
        return "hello:"+sid+":"+message;
    }

    /** 发送错误时的处理
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

}